﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace MyMusicPlay._4._0
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region 字段
        private PlayApplication PlayApplication { get; init; }
        private Media Media { get { return PlayApplication.GetModule<Media>(); } }
        private ScrollToPlaying ScrollToPlaying { get { return PlayApplication.GetModule<ScrollToPlaying>(); } }
        private DispositionApp Disposition { get { return PlayApplication.GetModule<DispositionApp>(); } }
        private MusicPlaying MusicPlaying { get { return PlayApplication.GetModule<MusicPlaying>(); } }
        private Rander Rander { get { return PlayApplication.GetModule<Rander>(); } }
        private DisPlayTextAnim DisPlayTextAnim { get { return PlayApplication.GetModule<DisPlayTextAnim>(); } }
        private MusicPlayingBoard MusicPlayingBoard { get { return PlayApplication.GetModule<MusicPlayingBoard>(); } }
        private MyMessageBox MyMessageBox { get { return PlayApplication.GetModule<MyMessageBox>(); } }

        #endregion
        public MainWindow()
        {
            InitializeComponent();

            PlayApplication = new PlayApplication(this);

            Media.LoadMusicList();//加载歌单

            PlayApplication.GetHook(typeof(MusicPlayingHook)).HookStart(() => { MusicPlaying.Playing(); });

            InitializeMoveView();//跳转页面

            MusicDisplayList.ContextMenu = PlayApplication.GetModule<RightMenu>().CreateMenuByMusicPlayingList();//加载歌曲表右键菜单

            Rander.UpdateColorByForeground();//加载文字颜色

            TaskbarView.ContextMenu = PlayApplication.GetModule<RightMenu>().CreateMenuByProgramMenu();//加载菜单栏右键菜单


            
            
        }

        #region 跳转页面
        public enum MoveViewEnum
        {
            NULL,
            PlayView,
            ConfigView
        }
        private Dictionary<MoveViewEnum, Grid> MoveViewDic = new();
        private MoveViewEnum CurrView = MoveViewEnum.NULL;
        private MoveViewEnum LastView = MoveViewEnum.NULL;
        public void InitializeMoveView()
        {
            var values = typeof(MoveViewEnum).GetEnumNames();
            foreach (var item in values)
            {
                var obj = FindName(item);
                var index = values.ToList().IndexOf(item);
                MoveViewDic.Add((MoveViewEnum)index, (Grid)obj);
            }

            //MoveView(MoveViewEnum.PlayView);
        }
        public Grid GetMoveView(MoveViewEnum moveViewEnum)
            => MoveViewDic[moveViewEnum];
        public double GetMoveViewHeight()
            => MoveView_Stap.ActualHeight;
        public void MoveView(MoveViewEnum moveView)
        {
            if (moveView == CurrView)
            {
                return;
            }
            LastView = CurrView;
            CurrView = moveView;
            if (LastView != MoveViewEnum.NULL)
            {
                var oldGrid = GetMoveView(LastView);
                //Animate.Deformation(oldGrid, Animate.direction.Height, oldGrid.ActualHeight, 0, 500);
                //DependencyProperty
                SY_Library.Animate.Double(oldGrid, Grid.HeightProperty, oldGrid.ActualHeight, 0, 500);
            }
            if (CurrView != MoveViewEnum.NULL)
            {
                var curGrid = GetMoveView(CurrView);
                SY_Library.Animate.Double(curGrid, Grid.HeightProperty, curGrid.ActualHeight, GetMoveViewHeight(), 500);
                //Animate.Deformation(curGrid, Animate.direction.Height, curGrid.ActualHeight, GetMoveViewHeight(), 500);
            }

        }

        #endregion


        /// <summary>
        /// 双击播放
        /// </summary>
        private void MusicDisplayList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var index = (sender as ListView).SelectedIndex;

            //查询当前歌曲是否在播放列表中,如果存在着不更新,否则更新列表
            //这个地方需要判断一下是否更新了播放列表
            if (_Retrieval_Judge)//当前是否是检索状态
            {
                if (RetrievalMusicList is not { Count: 0 })
                {
                    var music = RetrievalMusicList[index];
                    index = Media.CurDisplayList.GetMusicIndex(music);
                }
            }
            //获取当前歌曲
            var curMusic = Media.CurDisplayList.FirstOrDefault(u => u.Key == index).Value;
            if (curMusic == null)
            {
                //没有找到
            }

            var data = Media.CurPlayingList.FirstOrDefault(u => u.Value.Id == curMusic.Id);
            if (data.Value != null)
            {
                //从播放歌单播放
                Media.MusicPlaying(data.Key);
            }
            else
            {
                //更新列表播放
                Media.HandoffListAndPlay(index);
            }
        }
        /// <summary>
        /// 播放结束事件
        /// </summary>
        public void MediaElement_MediaEnded(object sender, RoutedEventArgs e)
        {
            MusicPlaying.NextMusicPlaying();
        }
        /// <summary>
        /// 准备完成
        /// </summary>
        public void MediaElement_MediaOpened(object sender, RoutedEventArgs e)
        {
            ScrollToPlaying.End();
            ScrollToPlaying.State(false);

            //DisPlayTextAnim.BeginAnim();//
            MusicPlayingBoard.SetTopBoard(Media.GetCurMusic);

            //临时窗口
           
        }
        /// <summary>
        /// 窗口关闭
        /// </summary>
        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            PlayApplication.GetHooks().ForEach(u => { u.HookStop(); });
            Disposition.WriteDispoition();
        }



        #region 修改配置
        public void UpdateMusicList(int index, string name, string path)
        {
            if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(name))
                return;
            //更改内存配置
            Media.UpdateMusicList(index, name, path);
            Media.LoadMusicList();
        }
        public void UpdateBackImage(string path)
        {
            if (string.IsNullOrEmpty(path))
                return;
            try
            {
                var image = new BitmapImage(new Uri(path));
                var brush = new ImageBrush(new BitmapImage(new Uri(path)));
                brush.Stretch = Stretch.UniformToFill;
                BackImage_Image.Background = brush;
            }
            catch (Exception ex)
            {
                Log.Write(ex.Message);
                BackImage_Image.Background = SY_Library.Color.BackColor(255, 0);
            }
        }
        public void UpdateBackEffect(double effect)
        {
            BlurEffect be = new BlurEffect();
            be.Radius = effect;
            BackImage_Image.Effect = be;
        }
        public void UpdateBackgroundColor(ColorJson rgb)
        {
            if (rgb is null)
                return;
            SolidColorBrush scb = new SolidColorBrush();
            scb.Color = Color.FromRgb(Convert.ToByte(rgb.R), Convert.ToByte(rgb.G), Convert.ToByte(rgb.B));
            MainGrid.Background = scb;
        }
        public void UpdateBackgroundColor(int index, int value)
        {
            var color = (MainGrid.Background as SolidColorBrush).Color;

            SolidColorBrush scb = new SolidColorBrush();
            switch (index)
            {
                case 0:
                    scb.Color = Color.FromRgb(Convert.ToByte(value), Convert.ToByte(color.G), Convert.ToByte(color.B));
                    break;
                case 1:
                    scb.Color = Color.FromRgb(Convert.ToByte(color.R), Convert.ToByte(value), Convert.ToByte(color.B));
                    break;
                case 2:
                    scb.Color = Color.FromRgb(Convert.ToByte(color.R), Convert.ToByte(color.G), Convert.ToByte(value));
                    break;
                default:
                    scb.Color = color;
                    break;
            }
            MainGrid.Background = scb;
            MainGrid.Background.Opacity = Disposition.ReadDispositionOfBackOpacity();
        }
        public void UpdateBackgroundOpacity(double opacity)
        {
            var color = Disposition.ReadDispositionOfBackgrounColor();
            MainGrid.Background = SY_Library.Color.BackColor(Convert.ToByte(color.R), Convert.ToByte(color.G), Convert.ToByte(color.B));
            MainGrid.Background.Opacity = opacity;
        }
        public void UpdateMusicPlayingBoardBackImage(string path)
        {
            if (string.IsNullOrEmpty(path))
                return;
            try
            {
                var image = new BitmapImage(new Uri(path));
                var brush = new ImageBrush(new BitmapImage(new Uri(path)));
                brush.Stretch = Stretch.UniformToFill;
                PlayBoardHeightSet.Background = brush;
            }
            catch (Exception ex)
            {
                Log.Write(ex.Message);
                PlayBoardHeightSet.Background = SY_Library.Color.BackColor(255, 0);
            }
        }
        public void UpdateMusicPlayingBoardBackEffect(double effect)
        {
            BlurEffect be = new BlurEffect();
            be.Radius = effect;
            PlayBoardHeightSet.Effect = be;
        }
        public void UpdateMusicPlayingBoardOpacity(double opacity)
        {
            PlayBoardHeightSet.Background.Opacity = opacity;
        }
        #endregion



        private void NotifyIconPlaying_Click(object sender, RoutedEventArgs e)
        {
            MusicPlaying.Playing();
        }

        private void WindowsMove_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == System.Windows.Input.MouseButtonState.Pressed)
            {
                this.DragMove();
            }
        }

        private void ShutDown_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void Shrink_MouseUp(object sender, MouseButtonEventArgs e)
        {
            this.Visibility = Visibility.Hidden;
        }



        bool MoveViewjudge = false;
        int MoveViewSecond = 0;
        private void MainWindow_SizeChange(object sender, SizeChangedEventArgs e)
        {
            if (!MoveViewjudge)
            {
                MoveViewjudge = true;
                Task.Run(() =>
                {
                    while (MoveViewjudge)
                    {
                        Task.Delay(500).Wait();
                        if (DateTime.Now.Second - MoveViewSecond == 1)
                        {
                            MoveViewjudge = false;
                            var cur = GetMoveView(CurrView);
                            if (cur != null)
                            {
                                cur.Dispatcher.Invoke(() =>
                                {
                                    SY_Library.Animate.Double(cur, Grid.HeightProperty, cur.ActualHeight, this.ActualHeight - 30, 200);
                                });
                            }
                        }
                    }
                });
            }
            MoveViewSecond = DateTime.Now.Second;
        }

        //托盘双击事件[显形]
        private void TrayDoubleClick(object sender, RoutedEventArgs e)
        {
            this.Visibility = Visibility.Visible;
        }


    }

}

